package com.k2.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.k2.gulimall.product.service.CategoryBrandRelationService;
import com.k2.gulimall.product.vo.CateLog2Vo;
import com.mysql.cj.util.TimeUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.k2.common.utils.PageUtils;
import com.k2.common.utils.Query;

import com.k2.gulimall.product.dao.CategoryDao;
import com.k2.gulimall.product.entity.CategoryEntity;
import com.k2.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate StringRedisTemplate;

//    @Autowired
//    Redisson Redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //组装成父子的树形结构
        //找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    //查询首页的一级分类
    //需要缓存的数据都来指定放到哪个名字的缓存
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

//    @Cacheable(value = {"category"},key = "#root.methodName")
    @Override
    public Map<String, List<CateLog2Vo>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0l);
        //封装数据
        Map<String, List<CateLog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> CategoryEntity = getParent_cid(selectList, v.getCatId());
            //封装上面的结果
            List<CateLog2Vo> collect = null;

            if (CategoryEntity != null) {
                collect = CategoryEntity.stream().map(l2 -> {
                    CateLog2Vo cateLog2Vo = new CateLog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> Level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (Level3Catelog != null) {
                        List<CateLog2Vo.CateLog3Vo> collect1 = Level3Catelog.stream().map(l3 -> {
                            //封装成指定格式
                            CateLog2Vo.CateLog3Vo cateLog3Vo = new CateLog2Vo.CateLog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return cateLog3Vo;
                        }).collect(Collectors.toList());
                        cateLog2Vo.setCatalog3List(collect1);
                    }
                    return cateLog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;

        }));
        return parent_cid;
    }

    //    @Override
    public Map<String, List<CateLog2Vo>> getCatalogJson2() {
        /**
         * 空结果缓存，解决缓存穿透
         * 设置过期时间（加随机值），解决缓存雪崩
         * 加锁，解决缓存击穿
         */
        //给缓存中放json字符串，拿到的json字符串还要逆转为能用的对象类型
        //加入缓存逻辑，缓存中存的数据是json字符串
        //json跨语言跨平台兼容
        String catalogJSON = StringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //缓存中没有查询数据库
            Map<String, List<CateLog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
            return catalogJsonFromDb;
        }
        Map<String, List<CateLog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<CateLog2Vo>>>() {
        });
        return result;
    }


//    public Map<String, List<CateLog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
//        //锁的名字：锁的粒度，越细越快
//        RLock lock = Redisson.getLock("CatalogJson-lock");
//        Map<String, List<CateLog2Vo>> dataFromDb;
//        try {
//            dataFromDb = getDataFromDb();
//        } finally {
//        }
//        return dataFromDb;
//    }


    /**
     * 常超杰
     * @return
     */
    public Map<String, List<CateLog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //占分布式锁
        Boolean lock = StringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //设置过期时间
            //过期时间必须和加锁是同步的，原子的
            StringRedisTemplate.expire("lock", 30, TimeUnit.SECONDS);

            Map<String, List<CateLog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                //删除锁
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                Long lock1 = StringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"), uuid);
            }


            //获取值对比+对比成功操作=原子操作 lua脚本解锁
//            String lockValue = StringRedisTemplate.opsForValue().get("lock");
//            if (uuid.equals(lockValue)) {
//                //删除我自己的锁
//                StringRedisTemplate.delete("lock");//删除锁
//            }
            //加锁成功执行业务
            return dataFromDb;
        } else {
            //加锁失败重试
            //休眠100ms
            return getCatalogJsonFromDbWithRedisLock();//自旋的方式
        }
    }


    /**
     * 常超杰
     * @return
     */
    private Map<String, List<CateLog2Vo>> getDataFromDb() {
        //得到锁以后，应该再去缓存中确定一次，如果没有才需要继续查询
        String catalogJSON = StringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            //缓存不为null直接返回
            Map<String, List<CateLog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<CateLog2Vo>>>() {
            });
            return result;

        }
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0l);
        //封装数据
        Map<String, List<CateLog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> CategoryEntity = getParent_cid(selectList, v.getCatId());
            //封装上面的结果
            List<CateLog2Vo> collect = null;

            if (CategoryEntity != null) {
                collect = CategoryEntity.stream().map(l2 -> {
                    CateLog2Vo cateLog2Vo = new CateLog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> Level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (Level3Catelog != null) {
                        List<CateLog2Vo.CateLog3Vo> collect1 = Level3Catelog.stream().map(l3 -> {
                            //封装成指定格式
                            CateLog2Vo.CateLog3Vo cateLog3Vo = new CateLog2Vo.CateLog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return cateLog3Vo;
                        }).collect(Collectors.toList());
                        cateLog2Vo.setCatalog3List(collect1);

                    }
                    return cateLog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        //查询到的数据再放入缓存，将数据转为json放在缓存中
        String s = JSON.toJSONString(parent_cid);
        StringRedisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }


    /**
     * 常超杰
     * @return
     */
    //从数据库查询比并封装数据
    public Map<String, List<CateLog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        /**
         * 将数据的多次查询变为一次
         */
        //只要是同一把锁，就能锁住这个锁的所有线程
        synchronized (this) {
            //得到锁以后，应该再去缓存中确定一次，如果没有才需要继续查询
            return getDataFromDb();
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
//            return categoryEntity.getParentCid() == root.getCatId();
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //找到所有子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}